﻿using AutoMapper;
using AutoMapper.DTO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using Network.Library;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Tool.Model;

namespace Web.Manage.App_Start
{
    public static class AdminStartupConfigure
    {

        private static readonly IEnumerable<string> _VersionList = typeof(ApiVersionsEnum).GetEnumNames().ToList().OrderByDescending(w => w);

        /// <summary>
        /// 将服务添加到容器
        /// </summary>
        /// <param name="services"></param>
        /// <param name="Configuration"></param>
        /// <param name="_IWebHostEnvironment"></param>
        public static void AdminConfigureServices(this IServiceCollection services, IConfiguration Configuration, IHostingEnvironment _IWebHostEnvironment)
        {
            #region 跨域配置
            //配置跨域处理
            services.AddCors(options =>
            {
                options.AddPolicy("AllowSpecificOrigin", builder =>
                {
                    builder
                    .WithOrigins("http://localhost:64251")
                    .AllowAnyOrigin() //允许任何来源的主机访问
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();//指定处理cookie
                });
            });
            #endregion

            #region Session
            //启用内存缓存(该步骤需在AddSession()调用前使用)
            //启用session之前必须先添加内存
            services.AddDistributedMemoryCache();

            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(60 * 2);//设置session的过期时间
                options.Cookie.HttpOnly = true;//设置在浏览器不能通过js获得该cookie的值
                options.Cookie.IsEssential = true;
                //防止edge浏览器访问session丢失问题
                options.Cookie.SameSite = SameSiteMode.None;
            });

            #endregion

            #region HttpContext
            //注册HttpContextHelper类型服务
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            #endregion

            #region AutoMapper
            //AutoMapper初始化
            services.AddAutoMapper(Mappings.GetProfileTypes());
            #endregion

            //#region Ueditor
            ////Ueditor  编辑器 服务端 注入  configFileRelativePath: "wwwroot/admin/libs/nUeditor/net/config.json", isCacheConfig: false, basePath: "C:/basepath"
            //services.AddUEditorService(
            //        configFileRelativePath: _IWebHostEnvironment.WebRootPath + "/admin/libs/neditor/net/config.json",
            //        isCacheConfig: false,
            //        basePath: _IWebHostEnvironment.WebRootPath + "/admin/libs/neditor/net/"
            //    );
            //#endregion

            #region Swagger
            //注册Swagger生成器，定义一个和多个Swagger 文档
            //services.AddSwaggerGen(option =>
            //{
            //    foreach (var item in _VersionList)
            //    {
            //        var _SwaggerInfo = new Info();
            //        _SwaggerInfo.Version = item;
            //        //_SwaggerInfo.Title = "v_" + item;
            //        _SwaggerInfo.Description = "author：hzy";
            //        //_SwaggerInfo.TermsOfService = "None";
            //        option.SwaggerDoc(item, _SwaggerInfo);
            //    }
            //    // 为 Swagger JSON and UI设置xml文档注释路径
            //    var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录（绝对，不受工作目录影响，建议采用此方法获取路径）
            //    var xmlPath = Path.Combine(basePath, "App.xml");
            //    option.IncludeXmlComments(xmlPath);
            //    option.OperationFilter<Aop.SwaggerParameterFilter>(); // 手动高亮
            //});
            #endregion
        }

        /// <summary>
        /// 配置http请求管道
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        /// <param name="loggerFactory"></param>
        /// <param name="applicationLifetime"></param>
        public static void AdminConfigure(this IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime applicationLifetime)
        {

            #region nlog 日志
            ////初始化NLog
            //LogHelper.Init(app, env, loggerFactory);

            ////程序启动
            //applicationLifetime.ApplicationStarted.Register(() =>
            //{
            //    Tools.Log.Write("App启动");
            //});
            ////程序正在结束中
            //applicationLifetime.ApplicationStopping.Register(() =>
            //{
            //    Tools.Log.Write("App结束中...");
            //});
            ////程序已结束
            //applicationLifetime.ApplicationStopped.Register(() =>
            //{
            //    Tools.Log.Write("App已结束");
            //});
            //applicationLifetime.StopApplication();//停止程序
            #endregion

            #region Session
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseSession();//UseSession配置在UseMvc之前    开启session
            #endregion

            #region HttpContext
            //将 对象 IHttpContextAccessor 注入 HttpContextHelper 静态对象中             
            HttpContextHelper.Configure(app.ApplicationServices.GetRequiredService<IHttpContextAccessor>());
            #endregion

            #region AutoMapper
            Mappings.RegisterMappings();
            #endregion

            #region 错误处理
            app.UseStatusCodePagesWithReExecute("/Admin/Error/Page");
            #endregion
 
            #region 使用跨域
            app.UseCors("AllowSpecificOrigin");
            #endregion

            #region 服务器资源路径置换
            //服务器资源路径置换，这样可以防止客户端猜测服务端文件路径，制造一个虚拟的隐射进行访问，提高了安全性。
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot/Files")),
                RequestPath = new PathString("/src")
            });
            #endregion

            #region Swagger
            ////启用中间件服务生成Swagger作为JSON终结点
            //app.UseSwagger();
            ////启用中间件服务对swagger-ui，指定Swagger JSON终结点
            //app.UseSwaggerUI(option =>
            //{
            //    foreach (var item in _VersionList) option.SwaggerEndpoint($"/swagger/{item}/swagger.json", item);
            //    option.RoutePrefix = "swagger";
            //});
            #endregion

        }
    }
}
